package main

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/broker"
	"mqtt/message"
	_ "github.com/micro/go-plugins/broker/mqtt/v2" //init初始化
	"github.com/micro/go-plugins/broker/mqtt/v2"
)

/**
先订阅，后发布
 go run client.go
 发生 github.com/eclipse/paho%2emqtt%2egolang.(*router)  错误问题
 问题解决：安装go get github.com/eclipse/paho.mqtt.golang
 */
func main(){
	service := micro.NewService(
		micro.Name("mqtt-client"),
		micro.Version("v1.0.0"),
		micro.Broker(mqtt.NewBroker()),
		)
	service.Init()
	//获取代理
	pubSub := service.Server().Options().Broker
	//获取链接
	err := pubSub.Connect()
	if err !=nil {
		panic(err)
	}
	//消息订阅
	subscriber,err := pubSub.Subscribe("mqtt-test-msg",func(event broker.Event)error{
		//获取消息
		msg := event.Message()
		//获取主题
		topic := event.Topic()
		switch msg.Header["data_type"] {
		case "input":
			parasType1(topic,msg)
		case "struct":
			parasType2(topic,msg)
		}
		return nil
	})
	if err!=nil{
		fmt.Println(subscriber.Topic(),"主题订阅失败！ ",err.Error())
	}else {
		fmt.Println(subscriber.Topic(),"主题订阅成功！")
	}
	//运行服务
	service.Run()
	defer func() {
		fmt.Println("client close conn and Unsubscribe")
		pubSub.Disconnect()//关闭链接
		subscriber.Unsubscribe()//取消订阅
	}()
}
func parasType1(topic string,msg *broker.Message){
	fmt.Println("收到input消息：")
	fmt.Println("主题: ",topic)
	fmt.Println("Header:",msg.Header)
	fmt.Println("内容：",string(msg.Body),"\n")//[]byte -> string
}
func parasType2(topic string,msg *broker.Message){
	//反序列化 解码数据
	data := message.Student{}
	if err := proto.Unmarshal(msg.Body,&data);err!=nil{
		panic(err)
	}
	fmt.Println("收到struct消息：")
	fmt.Println("主题: ",topic)
	fmt.Println("Header:",msg.Header)
	fmt.Println("内容：",data,"\n")
}
